package com.kolakcc.loljclient.controller;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.concurrent.ExecutionException;

import javax.swing.SwingWorker;

import com.gvaneyck.rtmp.TypedObject;
import com.kolakcc.loljclient.StartupClass;
import com.kolakcc.loljclient.model.RecentGame;
import com.kolakcc.loljclient.model.swing.RecentGamesListModel;
import com.kolakcc.loljclient.view.ProfileView;

public class ProfileController extends KolaController implements MouseListener {
	ProfileView view;
	SwingWorker<TypedObject, Void> profileWorker;

	public RecentGamesListModel gamesListModel;

	public ProfileController() {
		this.view = new ProfileView();
		this.setView(this.view);
		this.initalizeWorkers();
		this.view.recentMatchesList.addMouseListener(this);
		this.profileWorker.execute();
	}

	public void initalizeWorkers() {
		this.profileWorker = new SwingWorker<TypedObject, Void>() {
			public TypedObject doInBackground() throws Exception {
				int id = 0;
				int accountID = 0;
				try {
					id = StartupClass.Client.invoke("clientFacadeService",
							"getLoginDataPacketForUser", new Object[] {});
					TypedObject summoner = StartupClass.Client.getResult(id)
							.getTO("data").getTO("body")
							.getTO("allSummonerData").getTO("summoner");
					accountID = summoner.getInt("acctId");
					id = StartupClass.Client.invoke("playerStatsService",
							"getRecentGames", new Object[] { accountID });
				} catch (Exception e) {
					ProfileController.this.HandleException(e);
				}
				return StartupClass.Client.getResult(id).getTO("data")
						.getTO("body");
			}

			public void done() {
				try {
					ProfileController.this.gamesListModel = new RecentGamesListModel(
							this.get().getArray("gameStatistics"));
					ProfileController.this.view.recentMatchesList
							.setModel(ProfileController.this.gamesListModel);
					ProfileController.this.view.recentMatchesList
							.getSelectionModel().addSelectionInterval(0, 0);
					ProfileController.this.mouseClicked(null);
				} catch (InterruptedException | ExecutionException e) {
					e.printStackTrace();
					ProfileController.this.initalizeWorkers();
				}
			}
		};
	}

	public void mouseClicked(MouseEvent e) {
		RecentGame game = this.gamesListModel
				.getGameAt(this.view.recentMatchesList.getSelectedIndex());
		this.view.setItems(game.getStatistic("ITEM0"),
				game.getStatistic("ITEM1"), game.getStatistic("ITEM2"),
				game.getStatistic("ITEM3"), game.getStatistic("ITEM4"),
				game.getStatistic("ITEM5"));
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

}
